//
//  KBPlaceholdTextView.swift
//  KimboWeiBoSwift
//
//  Created by kimbo on 15/12/27.
//  Copyright © 2015年 kimbo. All rights reserved.
//

import UIKit

class KBPlaceholdTextView: UITextView {
    
    // MARK: - 属性
    var placeholdText: String? {
        didSet {
            placeholdLabel.text = placeholdText
            placeholdLabel.sizeToFit()
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
        
        // 代理一对一，外面已经用了代理，这里再用会被覆盖，所以用通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: self)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // 通知回调方法
    @objc private func textDidChange() {
        placeholdLabel.hidden = self.hasText()
    }
    
    private func setupUI() {
        addSubview(placeholdLabel)
        
        //添加约束
        placeholdLabel.translatesAutoresizingMaskIntoConstraints = false
        //Top
        addConstraint(NSLayoutConstraint(item: placeholdLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        //Leading
        addConstraint(NSLayoutConstraint(item: placeholdLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
    }

    // MARK: - 懒加载
    private lazy var placeholdLabel: UILabel = {
       let placeholdLabel = UILabel()
        
        placeholdLabel.font = UIFont.systemFontOfSize(18)
        
        placeholdLabel.textColor = UIColor.lightGrayColor()
        
        return placeholdLabel
    }()
}
